package com.fbli.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisUtil {
    private static Properties properties = new Properties();
    private static JedisPoolConfig config = new JedisPoolConfig();
    private static JedisPool pool;

    private JedisUtil() {

    }

    static {
        InputStream inputStream = JedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
        try {
            properties.load(inputStream);
            config.setMaxTotal(Integer.parseInt(properties.getProperty("redis.maxTotal")));
            config.setMaxIdle(Integer.parseInt(properties.getProperty("redis.maxIdle")));
            config.setMaxWaitMillis(Integer.parseInt(properties.getProperty("redis.maxWaitMillis")));
            config.setBlockWhenExhausted(true);
            pool = new JedisPool(config, properties.getProperty("redis.host"), Integer.parseInt(properties.getProperty("redis.port")));
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static Jedis getResource() {
        return pool.getResource();
    }

    public static void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    public static void shutdown() {
        if (pool != null) {
            if (pool.getNumActive() == 0) {
                pool.close();
            }
        }
    }
}
